import Vue from 'vue'
import Router from 'vue-router'
import {createRouterLayout} from 'vue-router-layout'
import store from './store'
import loading from "./plugins/loading";
import routes from './routes'
import i18n from "./i18n";
import qs from "querystring";

Vue.use(Router)

const RouterLayout = createRouterLayout(layout => {
    return import('@/layouts/' + layout + '.vue')
})

const router = new Router({
    routes: [
        {
            path: '/',
            component: RouterLayout,
            children: routes
        }
    ]
})

router.beforeEach((to, from, next) => {
    loading && loading.close();
    const vstore = localStorage.getItem("VueStore");
    if (vstore) {
        store.replaceState(Object.assign(store.state, JSON.parse(vstore)));
        if (store.state.locale) {
            i18n.locale = store.state.locale
        } else {
            i18n.locale = 'zh'
        }
        localStorage.removeItem("VueStore");
    }
    if (to.meta.anon) {
        next();
    } else if (store.state.user && store.state.user.token) {
        if (to.meta.password) {
            pwd(next)
        } else {
            next();
        }
    } else {
        next('/login')
    }
})

function pwd(next, msg) {
    const vm = i18n.vm,
        api = vm.api,
        http = vm.$http;
    swal({
        title: i18n.t('msg.password2'),
        text: msg,
        content: {
            element: "input",
            attributes: {
                placeholder: "请输入密码",
                type: "password",
            },
        },
        button: {
            text: i18n.t('btn.ok'),
            className: 'btn btn-gradient',
        }
    }).then(val => {
        if (!val) throw null;
        const params = {user_readpass: val};
        return http.post(api + 'UserLogin/checkreadpass', qs.stringify(params))
    }).then(response => {
        const data = response.data;
        if ('0' === data.code) {
            next();
        } else if (250 !== data.code) {
            pwd(next, data.msg)
        }
    }).catch(err => {
        next(false)
        if (!err) return;
        swal({
            title: i18n.t('msg.password2'),
            text: err.message,
            icon: 'error',
            button: {
                text: i18n.t('btn.ok'),
                className: 'btn btn-gradient',
            }
        })
    })
}

export default router;
